<!--
 * @Descripttion: 采购人-注册
 * @version:
 * @Author: 穆宏宇
 * @Date: 2020-09-21 10:36
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-04 16:17:04
-->
<template>
	<div class='form-box'>
		<!-- <div class="introduce">
			<p class="title">温馨提示</p>
			<p class="content">尊敬的客户您好，您的账户已创建完毕。请提供相关手续完成后续注册流程。包括所属组织机构、部门名称，审批流（下单人、审批人）信息。您可拨打客服电话，平台客服会协助您完成后续注册流程。</p>
			<div style="width: 100%;height:1px;background: #ccc;margin: 20px auto;"></div>
			<p class="title">采购用户注册流程</p>
			<p class="content">用户自行注册->注册完成登录平台->点击首页右上方工作台->进入后台管理->点击资质申请->采购人申请->下载授权委托书文件</p>
			<p class="content">将资质文件填写完成并加盖公章提交给平台。平台会为您完善其他信息，包括组织部门名称、分配角色以及绘制审批流。</p>
			<el-button @click="downloadFile" type="primary" style="margin-top: 30px;float: right;">授权委托书下载</el-button>
		</div> -->

		<!-- {{form}} -->
		<el-form v-if='isShow' ref='form' :model='form' label-width='120px' :rules='rules'>
			<el-row>
				<el-col :span='12'>
					<el-form-item class='form-box-label' label='组织机构选择' prop='orgId'>
						<el-cascader :options='purchaserOrgAll'
							:props="{ value: 'id', label: 'name', checkStrictly: 'true' }" v-model='form.orgId'
							:show-all-levels='false'>
						</el-cascader>
					</el-form-item>
				</el-col>
				<p v-if="this.form.auditStatus == 2">拒绝原因：{{this.form.refuseDetail}}</p>

				<!-- <div class="top">				  
				    <el-tooltip class="item" effect="dark" content="审批未通过提示" placement="top">
				      <el-button>审批未通过</el-button>
				    </el-tooltip>				     	
				  </div> -->

				<el-col :span='24'>
					<el-form-item class='form-box-label form-box-hint'>
						如没有找到您的组织机构，请和中心申请创建组织
					</el-form-item>
					<h3 class='form-box-title'>请填写组织信息</h3>
				</el-col>
				<el-col :span='12'>
					<el-form-item label='工号:' prop='employeeId'>
						<el-input v-model='form.employeeId' placeholder='请输入工号'>
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span='12'>
					<el-form-item label='办公电话:' prop='tel'>
						<el-input v-model='form.tel' placeholder='请输入办公电话'>
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span='24'>
					<el-col :span='12'>
						<el-form-item label='手机号:'>{{ mobile }}</el-form-item>
					</el-col>
					<el-col :span='12'>
						<el-form-item label='身份证号:' prop='idCard'>
							<el-input v-model='form.idCard' placeholder='请输入身份证号'>
							</el-input>
						</el-form-item>
					</el-col>
				</el-col>
				<el-col :span='12'>
					<el-form-item label='身份证正面:' prop='idCardFront'>
						<div style="float:left;">
							<div v-if="form.idCardFront">
								<div>
									<img :src="form.idCardFront"
										v-if="form.idCardFront.indexOf('www.ansteelmro.com') > -1" />
									<img :src="'http://www.ansteelmro.com' +  form.idCardFront" v-else />
								</div>
								<div>
									<el-button size="mini" @click="removeImg(form,'idCardFront','frontFileList')">移除
									</el-button>
									<span class="tips">( 移除后可重新上传 )</span>
								</div>
							</div>
							<el-upload v-else :class="{'limited':frontFileList.length>0}" list-type='picture-card'
								:action=fileUrl :data="{ fileType: 17}" :on-preview="handlePreview"
								:on-remove="(file, fileList)=>handleRemove(file, fileList,true)"
								:on-success="(res, file,fileList)=>handleAvatarSuccess(res, file,fileList,true)"
								:on-error="handleAvatarError" :before-upload="beforeAvatarUpload" :headers=fileHeaders
								multiple :limit="1" :on-exceed="handleExceed" :file-list="frontFileList">
								<i class='el-icon-plus'></i>
							</el-upload>
							<span class="tips">手机扫码二维码也可上传</span>
						</div>
						<!-- <div ref="qrCodeDiv" id="aaa"
							style="float:left;width:150px;height:150px;margin:0 20px;display:block;"></div> -->
					</el-form-item>
				</el-col>

				<el-col :span='12' class="pic">
					<el-form-item label='身份证反面:' prop='idCardBack'>
						<div style="float:left;">
							<div v-if="form.idCardBack">
								<div>
									<img :src="form.idCardBack"
										v-if="form.idCardBack.indexOf('www.ansteelmro.com') > -1" />
									<img :src="'http://www.ansteelmro.com' +  form.idCardBack" v-else />
								</div>
								<div>
									<el-button size="mini" @click="removeImg(form,'idCardBack','backFileList')">移除
									</el-button>
									<span class="tips">( 移除后可重新上传 )</span>
								</div>
							</div>
							<el-upload v-else :class="{'limited':backFileList.length>0}" list-type='picture-card'
								:action=fileUrl :data="{ fileType: 17}" :on-preview="handlePreview"
								:on-remove="(file, fileList)=>handleRemove(file, fileList,false)"
								:on-success="(res, file,fileList)=>handleAvatarSuccess(res, file,fileList,false)"
								:on-error="handleAvatarError" :before-upload="beforeAvatarUpload" :headers=fileHeaders
								multiple :limit="1" :on-exceed="handleExceed" :file-list="backFileList">
								<i class='el-icon-plus'></i>
							</el-upload>
							<span class="tips">手机扫码二维码也可上传</span>
						</div>
						<!-- <div ref="qrCodeDiv2" id="bbb"
							style="float:left;width:150px;height:150px;margin:0 20px;display:block;"></div> -->
					</el-form-item>
				</el-col>
				<el-col :span='24' class='submit' v-if="form.auditStatus != 0">
					<el-button type='primary' @click="submit('form')">提交</el-button>
				</el-col>
			</el-row>
		</el-form>
		<el-form v-else :model='form' label-width='120px'>
			<el-row>
				<el-col :span='12'>
					<el-form-item label='工号:'>{{ form.employeeId }}</el-form-item>
					<el-form-item label='手机号:'>{{ mobile }}</el-form-item>
					<el-form-item label='身份证正面:'>
						<img :src="cardFrontUrl" class="preview" @click="previewImg(cardFrontUrl)">
					</el-form-item>
					<el-form-item label='审核状态:' style='color: orange'>{{ auditStatusArr[form.auditStatus] }}
					</el-form-item>
				</el-col>
				<el-col :span='12'>
					<el-form-item label='办公电话:'>{{ form.tel }}</el-form-item>
					<el-form-item label='身份证号:'>{{ form.idCard }}</el-form-item>
					<el-form-item label='身份证反面:'>
						<img :src="cardBackUrl" alt="" class="preview" @click="previewImg(cardBackUrl)">
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<!-- 查看附件   -->
		<el-dialog :visible.sync='dialogVisible'>
			<img width='100%' :src='dialogImageUrl' alt='' />
		</el-dialog>

	</div>
</template>

<script>
	import QRCode from 'qrcodejs2'
	import {
		checkIdcard
	} from '@/validations/validate'
	import {
		createUuid
	} from '@/util/common'
	import {
		getVerification,
		getMobileverifycode,
		deleteFile,
		getFileUrl
	} from '@/api/common.api'
	import {
		getUserById,
		getPurchaserOrgAll,
		getPurchaser,
		registerPurchaser,
		getAllOrgList,
		insertTBizUserPurchase,
		selectTBizUserPurchaseList,
		selectTAuthUserOrg
	} from '@/api/admin.api'
	// 上传文件
	import {
		beforeUpload
	} from '@/util/common'
	// 上传文件
	import fileUpdata from '@/api/file.config'
	import commonImg from "@/views/admin/components/common-img";

	export default {
		inject: ['reload'], //注入刷新依赖
		name: 'purchaser-register',
		components: {
			commonImg
		},
		data() {
			return {
				// 附件
				fileHeaders: fileUpdata.headers(),
				fileUrl: fileUpdata.url,
				dialogVisible: false,
				dialogImageUrl: '',
				frontFileList: [], // 身份证正面
				backFileList: [], // 身份证反面
				cardFrontUrl: '',
				cardBackUrl: '',
				form: {
					orgId: '',
					employeeId: '',
					tel: '',
					mobileVerifyCode: '',
					imageVerifyCode: '',
					idCard: '',
					idCardBack: '', // 身份证背面图ID
					idCardFront: '' // 身份证正面图ID
				},
				isShow: true,
				count: 0,
				showCount: true, // 显示倒计时
				mobile: '',
				rules: {
					orgId: [{
						required: true,
						message: '请选组织机构',
						trigger: 'change'
					}],
					employeeId: [{
						required: true,
						message: '请输入工号',
						trigger: 'blur'
					}],
					tel: [{
							required: true,
							message: '请输入办公电话',
							trigger: 'blur'
						},
						{
							pattern: /(^(0[0-9]{2,3}\-)([2-9][0-9]{4,7})+(\-[0-9]{1,4})?$)/,
							message: '座机格式(区号-座机号码)',
							trigger: 'blur'
						}
					],
					mobileVerifyCode: [{
						required: true,
						message: '请输入手机验证码',
						trigger: 'blur'
					}],
					imageVerifyCode: [{
						required: true,
						message: '请输入验证码',
						trigger: 'blur'
					}],
					idCard: [{
							required: true,
							message: '请输入身份证号',
							trigger: 'blur'
						},
						{
							validator: checkIdcard,
							trigger: 'blur'
						}
					],
					idCardBack: [{
						required: true,
						message: '请选择身份证反面图',
						trigger: 'change'
					}],
					idCardFront: [{
						required: true,
						message: '请选择身份证正面图',
						trigger: 'change'
					}]
				},
				purchaserOrgAll: [],
				verifyCodeSrc: '',
				Uuid: '',
				auditStatusArr: [
					'申请正在审核中，请耐心等待～',
					'审核通过',
					'审核未通过'
				]
			}
		},
		watch: {},
		computed: {},
		created() {
			var that = this;
			// setTimeout(function() {
			// 	that.createQrCode();
			// 	that.createQrCode2();
			// }, 1000);

		},
		mounted() {
			// 查询用户信息
			// this.getUserFn()
			this.getPurchaserOrgAllFn();
			this.asd();
			// this.getDetail()
			// this.createQrCode();
		},
		methods: {
			//
			// getDetail() {
			// 	selectTBizUserPurchaseList({
			// 		userId: this.form.id
			// 	}).then(res => {
			// 		console.log(res)
			// 		this.form.employeeId=res.rows[0].employeeId

			// 	})
			// },
			selectTAuthUserOrg() {
				var that = this;
				var userId = localStorage.getItem("userId");
				selectTAuthUserOrg({
					userId: userId
				}).then(res => {
					if (res && res.length > 0) {
						that.form.orgId = res[0].orgId
						that.$forceUpdate()
						if (that.form.auditStatus == 2) {
							this.$alert('审批被拒,请重新提交。原因:' + this.form.refuseDetail, '提示', {
								confirmButtonText: '确定'
							})
						}
					}
				})
			},
			asd() {
				var that = this;
				var userId = localStorage.getItem("userId");
				selectTBizUserPurchaseList({
					createUser: userId
				}).then(res => {
					if (res && res.rows.length > 0) {
						that.form = res.rows[0]
						that.selectTAuthUserOrg();
						that.$forceUpdate()
					}
				})

			},
			createQrCode() {
				// this.$refs.qrCodeDiv.clear()
				var that = this;
				new QRCode(this.$refs.qrCodeDiv, {
					text: "http://www.ansteelmro.com?id=" + localStorage.getItem("userId") + "&type=idCardFront",
					width: 150,
					height: 150,
					colorDark: "#333333", //二维码颜色
					colorLight: "#ffffff", //二维码背景色
					correctLevel: QRCode.CorrectLevel.L, //容错率，L/M/H
					margin: 20
				})
				setTimeout(function() {
					var currentSrc = document.getElementById("aaa").childNodes[1].currentSrc;
					that.currentSrc = currentSrc;
				}, 100);
			},
			createQrCode2() {
				// this.$refs.qrCodeDiv.clear()
				var that = this;
				new QRCode(this.$refs.qrCodeDiv2, {
					text: "http://www.ansteelmro.com?id=" + localStorage.getItem("userId") + "&type=idCardBack",
					width: 150,
					height: 150,
					colorDark: "#333333", //二维码颜色
					colorLight: "#ffffff", //二维码背景色
					correctLevel: QRCode.CorrectLevel.L, //容错率，L/M/H
					margin: 20
				})
				setTimeout(function() {
					var currentSrc = document.getElementById("bbb").childNodes[1].currentSrc;
					that.currentSrc2 = currentSrc;
				}, 100);
			},
			downloadFile() {
				window.open("/admin/static/授权委托书.docx")
			},
			/**
			 * @description 预览身份证
			 * @author 穆宏宇
			 * @date 2020-10-26 11:03:18
			 * @param
			 * @return
			 * */
			previewImg(imgUrl) {
				this.dialogImageUrl = imgUrl
				this.dialogVisible = true
			},
			/**
			 * @description 查看文件信息
			 * @author 穆宏宇
			 * @date 2020-10-26 10:51:01
			 * @param
			 * @return
			 * */
			getFileUrlFn(fileId, isFront) {
				getFileUrl(17, fileId).then(res => {
					isFront ? (this.cardFrontUrl = res) : (this.cardBackUrl = res)
				})
			},
			/**
			 * @description
			 * @author 穆宏宇
			 * @date 2020-09-23 16:00:28
			 * @param
			 * @return
			 * */
			getUserFn() {
				// const id = this.$tools.localRead('userId')
				// getUserById(id).then((response) => {
				// 	this.mobile = response.mobile
				// })

				var mobile = localStorage.getItem("mobile");
				this.mobile = mobile
			},
			/**
			 * @description 获取采购人组织下拉框
			 * @author 穆宏宇
			 * @date 2020-09-23 14:55:45
			 * @param
			 * @return
			 * */
			getPurchaserOrgAllFn() {
				getAllOrgList()
					.then((response) => {
						this.purchaserOrgAll = response
					})
					.then(() => {
						// 获取组织后 获取详情 以便组织机构及联回显
						// this.getPurchaserFn()
					})
			},
			/**
			 * @description 获取倒计时
			 * @author 穆宏宇
			 * @date 2020-09-23 14:46:38
			 * @param
			 * @return
			 * */
			getCode() {
				const TIME_COUNT = 60
				if (!this.timer) {
					this.count = TIME_COUNT
					this.showCount = false
					this.timer = setInterval(() => {
						if (this.count > 0 && this.count <= TIME_COUNT) {
							this.count--
						} else {
							this.showCount = true
							clearInterval(this.timer)
							this.timer = null
						}
					}, 1000)
					if (this.mobile) {
						getMobileverifycode(this.mobile).then(() => {
							this.$message('发送成功！')
						})
					}
				}
			},
			// 组织选项是否允许编辑
			setTreeDisabled(array, disabled) {
				if (array && array.length > 0) {
					array.forEach(item => {
						item['disabled'] = disabled
						if ('children' in item) {
							this.setTreeDisabled(item.children, disabled)
						}
					})
				}
			},
			// 获取组织的ids
			collectId(data, id) {
				const list = []
				getAll(data, id)

				function getAll(data, id) {
					for (let i = 0; i < data.length; i++) {
						const cur = data[i]
						const aa = findPnodeId(cur, id)
						if (aa && aa !== '0') {
							list.unshift(aa)
							getAll(data, aa)
						}
					}
				}

				function findPnodeId(data, id) {
					let result
					if (!data) {
						return
					}
					for (let i = 0; i < data.children.length; i++) {
						const item = data.children[i]
						if (item.id === id) {
							result = data.id
							return result
						} else if (item.children && item.children.length > 0) {
							result = findPnodeId(item, id)
							if (result) {
								return result
							}
						}
					}
					return result
				}

				return [...list]
			},
			/**
			 * @description 获取采购人信息
			 * @author 穆宏宇
			 * @date 2020-09-22 18:58:26
			 * @param
			 * @return
			 * */
			getPurchaserFn() {
				const id = this.$tools.localRead('userId')
				getPurchaser(id).then((response) => {
					const tempTree = [...this.purchaserOrgAll]
					// 没有注册采购人
					if (!response.id) {
						if (response.orgId && response.orgId !== null) {

							// 查找组织机构父级及本级id
							const orgIds = this.collectId(tempTree, response.orgId)
							const arrLastId = this.purchaserOrgAll.filter(item => item.id === response.orgId)
							if (arrLastId.length > 0) {
								// 组织禁用
								this.setTreeDisabled(tempTree, true)
								this.purchaserOrgAll = tempTree
							}
							this.$set(this.form, 'orgId', [...orgIds, ...arrLastId])
						} else {
							// 组织机构激活
							this.setTreeDisabled(tempTree, false)
							this.purchaserOrgAll = tempTree
							this.$set(this.form, 'orgId', [])
						}
						// 获取验证码
						this.getVerificationCode()
						this.isShow = true
					}
					// 已注册采购人
					else {
						const obj = response
						if (obj.id) {
							obj.orgId = this.collectId(this.purchaserOrgAll, obj.orgId)
						}
						this.form = obj
						// this.form.orgId = ['0b655260fc9711ea99830242ac110002']
						if (response.auditStatus === '0' || response.auditStatus === '1') {
							this.isShow = false
							// 获取身份证正面图片url
							this.getFileUrlFn(this.form.idCardFront, true)
							// 获取身份证反面图片url
							this.getFileUrlFn(this.form.idCardBack, false)
						} else if (response.auditStatus === '2') {
							this.getVerificationCode()
							this.$alert('审核未通过，请修改信息后，再次提交！', '提示', {
								confirmButtonText: '确定'
							})
							this.isShow = true
						}
					}
				})
			},
			/**
			 * @description 获取验证码
			 * @author 穆宏宇
			 * @date 2020-09-18 15:46:36
			 * @param
			 * @return
			 * */
			getVerificationCode() {
				this.Uuid = createUuid()
				getVerification(this.Uuid)
					.then((response) => {
						// const src = 'data:image/pngbase64,' + btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
						this.verifyCodeSrc = 'data:image/png;base64,' + response
					})
					.catch((err) => {
						// this.$message({
						//   message: err.msg,
						//   type: 'error'
						// })
					})
			},
			// 预览附件
			handlePreview(file) {
				getFileUrl(file.fileType, file.id).then(res => {
					this.dialogImageUrl = res
					this.dialogVisible = true
				})
			},
			// 删除附件
			handleRemove(file, fileList, isCardFront) {
				isCardFront ? (this.frontFileList = []) : (this.backFileList = [])
				if (file && file.status === "success") {
					isCardFront ? (this.form.idCardFront = '') : (this.form.idCardBack = '')
					isCardFront ? (this.frontFileList = fileList) : (this.backFileList = fileList)
				}
			},
			handleExceed(files, fileList) {
				this.$message.warning(`最多可上传 1 个附件，您已超限`)
			},
			handleAvatarSuccess(res, file, fileList, isCardFront) {
				isCardFront ? (this.form.idCardFront = res.data) : (this.form.idCardBack = res.data)
				isCardFront ? (this.frontFileList = fileList) : (this.backFileList = fileList)
			},
			handleAvatarError(res, file) {
				this.$message.error("文件上传失败，请重试")
			},
			beforeAvatarUpload(file) {
				//const isJPG = file.type === 'image/jpeg';
				const typeList = ['png', 'jpg', 'jpeg']
				const isJPG = beforeUpload(file, typeList)
				const isLt5M = file.size / 1024 / 1024 < 5
				if (!isJPG) {
					this.$message.error('上传文件格式不符合!')
				}
				if (!isLt5M) {
					this.$message.error('上传证图片大小不能超过 5MB!')
				}
				return isJPG && isLt5M
			},
			/**
			 * @description 注册-采购人
			 * @author 穆宏宇
			 * @date 2020-09-22 19:26:30
			 * @param
			 * @return
			 * */
			submit(formName) {
				var that = this;
				this.$refs[formName].validate((valid) => {
					if (valid) {
						const id = this.$tools.localRead('userId')
						const orgId = that.form.orgId && that.form.orgId.length > 0 ? that.form.orgId[that.form
							.orgId.length - 1] : '';
							
						if (orgId == "e") {
							orgId = that.form.orgId
						}
						insertTBizUserPurchase({
									...this.form,
									orgId,
									mobile: this.mobile
								},
								this.Uuid,
								id
							)
							.then(() => {
								this.$confirm('提交成功', '提示', {
									confirmButtonText: '查看审核状态',
									showCancelButton: false,
									type: 'success',
									center: true
								}).then(() => {
									// // 获取采购人信息
									// this.getPurchaserFn()
									this.reload()
								})
							})
							.catch((err) => {
								this.getVerificationCode()
								// this.$message({
								//   message: err.msg,
								//   type: 'error'
								// })
							})
					}
				})
			},
			// 移除图片
			removeImg(target, key, fileList) {
				deleteFile(17, target[key])
				target[key] = ''
				this[fileList] = []
			}
		},
		beforeDestroy() {
			if (this.timer) {
				// window.clearInterval(this.timer) //清除定时器
				this.timer = null
			}
		}
	}
</script>

<style scoped lang='scss'>
	.form-box {
		background-color: white;
		height: calc(100% - 90px);

		&-hint {
			padding-top: 20px;
			color: red;
		}

		&-label {
			margin-bottom: 0;
		}

		&-title {
			padding: 22px 20px;
		}

		.submit {
			text-align: center;
			margin: 40px 0;
		}
	}

	.preview {
		width: 80px;
		height: 80px;
		cursor: pointer;
	}

	.tips {
		margin: 0 10px;
		font-size: 12px;
		color: $--color-warning;
	}
</style>
<style lang="scss">
	.limited .el-upload {
		display: none;
	}

	.introduce {
		width: 800px;
		margin: 0 auto;
	}

	.title {
		text-align: center;
		font-weight: bold;
		font-size: 20px;
	}

	.content {
		margin-top: 20px;
		font-size: 16px;
		text-indent: 2em;
		line-height: 30px;
	}

	.center {
		text-align: center;
	}

	.el-form img {
		max-width: 300px;
	}

	.top {
		color: #FF3C3C;

	}
</style>
